<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2017/11/13
 * Time: 18:49
 * 注册自动加载
 */

class Loader{

    public static $alias = ["app"=>__DIR__];
    public static function setAlias($name,$path)
    {
        static::$alias[$name] = $path;
    }
    public static function getAlias($name){
        return isset(static::$alias[$name]) ? static::$alias[$name] :"";
    }
    public static function loadClass($className)
    {
        $newClassName = str_replace("\\","/",$className);
        $aliasPos = strpos($className,"\\");
        if($aliasPos !== false){
            $alias = substr($className,0,$aliasPos);
        }else{
            $alias = $className;
        }
        $rootDir = static::getAlias($alias);
        if($alias === ""){
            return ;
        }
        $pos = strpos($newClassName, '/');
        $newClassName =  substr($newClassName, $pos+1);
        $fullPath = $rootDir."/".$newClassName.".php";
        if(!is_file($fullPath)){
            return ;
        }

        include $fullPath;

        if(!class_exists($className) && !interface_exists($className)){
            throw new \Exception("类{$className}不存在,请检查命名空间是否正确?");
        }
        return ;
    }
}

spl_autoload_register("Loader::loadClass");